package ext.tianma.part.AVLMaterial.process;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import wt.doc.WTDocument;
import wt.fc.PersistenceHelper;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.workflow.definer.WfProcessTemplate;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfEngineServerHelper;
import wt.workflow.engine.WfProcess;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.generic.erp.attributes.EnumerationUtil;
import ext.tianma.part.AVLMaterial.AVLUtil;
import ext.tianma.part.AVLMaterial.constants.RangeChangeConstants;
import ext.tianma.part.AVLMaterial.service.APLQuantityService;
import ext.tianma.part.AVLMaterial.service.AVLMaterialService;
import ext.tianma.util.TMUtil;
import ext.tianma.workflow.SubmitBomReview;

/**
 * 类名: RangeChange </br>
 * 包名: ext.tianma.part.AVLMaterial.process
 * 描述: 用量变更流程
 * @author xucr
 * 创建时间: 2020年11月10日
 * 发布版本: V1.0
 */
public class RangeChangeProcess extends DefaultObjectFormProcessor{
	
	@Override
	public FormResult doOperation(NmCommandBean arg0, List<ObjectBean> arg1) throws WTException {
		FormResult formresult = new FormResult();
		formresult.setStatus(FormProcessingStatus.SUCCESS);
		NmOid nmoid = arg0.getActionOid();
		if( nmoid != null ){
			boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
			try {
				WTPart currentPart = (WTPart) nmoid.getRefObject();
				// 参考 UpdateEffectPartNumberProcessors
				if( currentPart != null ){
					HttpServletRequest request = arg0.getRequest();
					List<String> ranges = new ArrayList<String>();
					if( request != null ){
						//分别获取选择的属性范围值
						JSONArray array = new JSONArray();
						JSONObject obj = null;
						Map<String, String> rangeMap = AVLUtil.getIBARangeValue(); //八大属性
						Map<String,String> maps = EnumerationUtil.getEnumerationValues("Level"); //等级枚举
						for(String range : RangeChangeConstants.USABLERANGES) {
							/**
							 * request.getParameterValues : 查询出来的是数组
							 * request.getParameter：查询出来的是字符串
							 */
							String isselect = request.getParameter("check_" + range); //复选框：是否选择
							String targetLevel = request.getParameter(range); //选择的目标等级
							String historyLevel = TMUtil.conversion(request.getParameter("history_" + range)); //当前等级，可能无值
//							String quantity = request.getParameter("quantity_" + range);//等级值
							String quantity = TMUtil.conversion(request.getParameter("quantity_" + range));//ERP用量
							
							if("on".equals(isselect)) { //标识选择了
								if(StringUtils.isEmpty(targetLevel)) {
									throw new WTException("请确认已勾选的进阶范围中，目标等级已选择!");
								} 
								/*else if(StringUtils.isEmpty(quantity)) {
									throw new WTException("请确认已勾选的进阶范围中，目标用量不能为空!");
								}*/ 
								else {
									if(targetLevel.equals(historyLevel)) {
										throw new WTException("请确认已勾选的进阶范围中，目标等级与当前等级不能一致");
									} else {
										obj = new JSONObject();
										obj.put(AVLMaterialService.RANGE, range);
										obj.put(AVLMaterialService.RANGE_VALUE, TMUtil.conversion(rangeMap.get(range)));
										obj.put(AVLMaterialService.TARGETLEVEL, targetLevel);
										obj.put(AVLMaterialService.TARGETLEVEL_VALUE, TMUtil.conversion(maps.get(targetLevel)));
										obj.put(AVLMaterialService.HISTORYLEVEL, historyLevel);
										obj.put(AVLMaterialService.HISTORYLEVEL_VALUE, TMUtil.conversion(maps.get(historyLevel)));
										obj.put(AVLMaterialService.QUANTITY, quantity); //手动启动时，ERP用量
										array.put(obj);
										ranges.add(range);
									}
								}
							}
						}
						
						if(array.length() > 0) {
							String[] rangeArray = new String[ranges.size()];
							startProcess(currentPart, array, ranges.toArray(rangeArray), RangeChangeConstants.PROCESSTYPE[1]);
							
							FeedbackMessage feedbackmessage = new FeedbackMessage(
									FeedbackType.SUCCESS, null, RangeChangeConstants.PROCESSNAME + "启动成功", null, new String[] {});
							formresult.addFeedbackMessage(feedbackmessage);
						} else {
							throw new WTException("请选择进阶信息");
						}
					}
				}	
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {
				SessionServerHelper.manager.setAccessEnforced(flag);
			}
		}
		return formresult;
	}
	
	/**
	 * 启动流程
	 * @param doc 流程主对象
	 * @param changeData 变更数据
	 * @param processType 流程类型：自动/手动
	 * @return
	 * @author xucr
	 * @CreateDate 2020年11月10日
	 */
	private static WfProcess startProcess(WTDocument doc, Map<String, Object> maps) {
		WfProcess wfprocess = null;
		try {
			//获取流程模板
			WfProcessTemplate wfprocessTemplate = SubmitBomReview.getWfProcessTemplateByName(RangeChangeConstants.ADVANCED_WFPROCESSTEMPLATE_NAME);
			WTPrincipal wtprincipal = SessionHelper.manager.getPrincipal();
			String processName = RangeChangeConstants.PROCESSNAME + "_" + doc.getNumber();
			WTPrincipalReference wtprincipalreference = WTPrincipalReference.newWTPrincipalReference(wtprincipal);
		
			wfprocess = WfEngineHelper.service.createProcess(
					wfprocessTemplate, doc.getLifeCycleTemplate(),doc.getContainerReference());
			WfEngineServerHelper.service.setPrimaryBusinessObject(wfprocess,doc);
			wfprocess.setName(processName);
			
			ProcessData processdata = wfprocess.getContext();
			wfprocess.setCreator(wtprincipalreference);
			//设置流程变量
			if(null != maps && maps.size() > 0) {
				for(String key : maps.keySet()) {
					processdata.setValue(key, maps.get(key));
				}
			}
			wfprocess = (WfProcess)PersistenceHelper.manager.save(wfprocess);	
			wfprocess.start(processdata, true, doc.getContainerReference());
		} catch (WTException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		}
		return wfprocess;
	}
	
	/**
	 * 启动流程（自动/手动）
	 * @param currentPart
	 * @param array 单个APL材料要变更的数据集
	 * @param rangeArray 单个APL材料中，使用范围key
	 * @param processType 流程类型：自动/手动
	 * @author xucr
	 * @throws JSONException 
	 * @throws WTException 
	 * @CreateDate 2020年11月13日
	 */
	public static void startProcess(WTPart currentPart, JSONArray array, String[] rangeArray, String processType) throws JSONException, WTException {
		boolean isExist = AVLUtil.checkProcess(currentPart, true);
		if(isExist) {
			throw new WTException("材料 "+currentPart.getNumber()+" 已在进阶审批当中，不能重复提交!");
		} else {
//			//一个APL材料，只有一个进阶文档，APL材料可能会走多次，均使用这个文档
//			WTDocument doc = AVLUtil.getDoc(currentPart, RangeChangeConstants.APLREPORT);
			
			//一个流程一个文档，APL材料可能会走多次，会对应多个文档
			try {
				WTDocument doc = AVLUtil.createDoc(currentPart.getNumber() + "进阶报告", "", "");
				//启动流程，并设置流程变量
				Map<String, Object> map = new HashMap<String, Object>();
				map.put(RangeChangeConstants.FIRSTPROCESSRANGE, StringUtils.join(rangeArray, ","));
				map.put(RangeChangeConstants.CHANGEDATA, array.toString());
				map.put(RangeChangeConstants.PROCESSTYPE_NAME, processType);
				map.put(RangeChangeConstants.PARTMASTER, currentPart.getMasterReference().getObject());
				startProcess(doc, map);
				//修改APL用量表数据：流程中、不进阶
				WTPartMaster master = (WTPartMaster) currentPart.getMasterReference().getObject();
				APLQuantityService.updateAPLQuantity(master, rangeArray, true, false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
